﻿var fs = require('fs');
var workPath = fs.dirname(fs.absolute(phantom.casperScript));
var util = require(workPath+fs.separator+'util');
var cfg = util.getDefaultCfg();
// cfg.pageSettings.loadImages = false;
// cfg.pageSettings.loadPlugins = false;
cfg.verbose = false;
util.log2c = util.noop;
// cfg.logLevel = 'error';
var casper = util.getCasper(cfg);
var logf = workPath+fs.separator+'linkong.log';

casper.rtn = {result:true,info:[],msg:[]};
casper.dateStr = phantom.casperArgs.args[0]||'周一';
casper.rtn.info.push(casper.dateStr);
casper.start('http://www.gewara.com/sport/37597055').then(function() {
    this.page.injectJs(workPath+fs.separator+'jquery-1.8.2.min.js');
    var dateStr = this.dateStr;
    var bookUrl = this.evaluate(function(dateStr){
        var url =null;
        var bookLink = jQuery('.opitime b:contains("'+dateStr+'")').parents('li').find('.opiurl a.bigBt');
        if(bookLink.size()){
            url = bookLink.attr('href');
        }else{
            url = false;
        }
        return url;
    },dateStr);

    if(bookUrl && bookUrl!==false){
        util.log2c('bookUrl==>'+bookUrl);
        this.open('http://www.gewara.com/'+bookUrl).then(function(){
            this.page.injectJs(workPath+fs.separator+'jquery-1.8.2.min.js');
            var hasSeatCount = this.evaluate(function(){
                return jQuery('.mod_tabs .inner .hasSeat').size();
            });
            this.rtn.hasSeatCount = hasSeatCount;
            this.rtn.dateStr = this.evaluate(function(){
                return jQuery('.nav_tabs .select').text();
            });
            util.log2c("hasSeatCount=>"+hasSeatCount);

//            this.captureSelector('e:/linkong.png', 'body');
            var imgData =  this.captureBase64('png', 'div.mod_tabs');
            this.rtn.imgData = imgData;
            this.rtn.bookUrl = bookUrl;
//            util.log2c(imgData);
        });
    }else{
        var msg = 'bookUrl find failed. maybe too early to find.';
        util.log2c(msg);
        this.rtn.result = false;
        this.rtn.info.push(msg);
    }
});


casper.run(function(){
    // this.test.renderResults(true).exit();
    this.echo(JSON.stringify(this.rtn)).exit();
});
